<template>
  <a-modal
    v-model:visible="visible"
    title="批量新增用户"
    :width="600"
    :mask-closable="false"
    :esc-to-close="false"
    ok-text="确认导入"
    cancel-text="取消"
    @before-ok="handleImport"
    @close="handleClose"
  >
    <div class="batch-import-content">
      <a-alert type="info" :show-icon="false" style="margin-bottom: 20px">
        <div>请上传Excel表格，A2单元格开始放置手机号</div>
        <div>支持格式：.xlsx、.xls</div>
      </a-alert>

      <a-upload
        ref="uploadRef"
        :custom-request="handleUpload"
        :limit="1"
        :show-retry-button="false"
        :show-cancel-button="false"
        :file-list="fileList"
        accept=".xls,.xlsx,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        draggable
        tip="点击或拖拽文件到此区域上传"
      >
        <template #upload-button>
          <div class="upload-area">
            <icon-upload size="48" style="color: #3370ff;" />
            <div style="margin-top: 10px; color: #86909c;">点击或拖拽Excel文件到此区域</div>
          </div>
        </template>
      </a-upload>

      <!-- 导入结果显示 -->
      <div v-if="importResult" class="import-result">
        <a-divider>导入结果</a-divider>
        <a-space size="large">
          <a-statistic title="成功导入" :value="importResult.successfulCount" />
          <a-statistic title="导入失败" :value="importResult.failureCount" />
        </a-space>

        <div v-if="importResult.failedMobiles && importResult.failedMobiles.length > 0" style="margin-top: 20px;">
          <a-alert type="warning" :show-icon="false">
            <template #title>
              <div>失败的手机号 ({{ importResult.failedMobiles.length }}个)</div>
            </template>
            <div class="failed-mobiles">
              <a-tag v-for="mobile in importResult.failedMobiles" :key="mobile" color="red" size="small">
                {{ mobile }}
              </a-tag>
            </div>
            <template #action>
              <a-button size="small" @click="downloadFailedMobiles">下载失败列表</a-button>
            </template>
          </a-alert>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { Message, type RequestOption } from '@arco-design/web-vue'
import { type BatchImportUserResp, batchImportUser } from '@/apis/system'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const visible = ref(false)
const fileList = ref([])
const uploadRef = ref()
const importResult = ref<BatchImportUserResp | null>(null)
const currentFile = ref<File | null>(null)

// 打开模态框
const onOpen = () => {
  visible.value = true
  reset()
}

// 重置状态
const reset = () => {
  fileList.value = []
  importResult.value = null
  currentFile.value = null
}

// 关闭模态框
const handleClose = () => {
  reset()
}

// 处理文件上传
const handleUpload = (options: RequestOption) => {
  const { fileItem, onSuccess, onError } = options

  if (!fileItem.file) {
    onError(new Error('文件不存在'))
    return
  }

  // 验证文件类型
  const allowedTypes = [
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  ]

  if (!allowedTypes.includes(fileItem.file.type)
    && !fileItem.name?.endsWith('.xls')
    && !fileItem.name?.endsWith('.xlsx')) {
    Message.error('请上传Excel文件（.xls或.xlsx格式）')
    onError(new Error('文件格式不正确'))
    return
  }

  // 验证文件大小（限制10MB）
  if (fileItem.file.size > 10 * 1024 * 1024) {
    Message.error('文件大小不能超过10MB')
    onError(new Error('文件过大'))
    return
  }

  currentFile.value = fileItem.file as File
  Message.success('文件上传成功，请点击确认导入')
  onSuccess()
}

// 执行导入
const handleImport = async () => {
  if (!currentFile.value) {
    Message.error('请先上传Excel文件')
    return false
  }

  try {
    const response = await batchImportUser(currentFile.value)
    importResult.value = response.data

    const { successfulCount, failureCount } = response.data
    if (failureCount === 0) {
      Message.success(`批量导入成功！共导入 ${successfulCount} 个用户`)
      emit('save-success')
      return true
    } else {
      Message.warning(`导入完成！成功 ${successfulCount} 个，失败 ${failureCount} 个`)
      emit('save-success')
      return false // 保持模态框打开以显示失败结果
    }
  } catch (error) {
    Message.error('导入失败，请检查文件格式和内容')
    return false
  }
}

// 下载失败手机号列表
const downloadFailedMobiles = async () => {
  if (!importResult.value?.failedMobiles?.length) {
    return
  }

  try {
    // 动态导入xlsx库
    const XLSX = await import('xlsx')

    // 创建工作表数据
    const wsData = [
      ['失败手机号'], // A1标题
      ...importResult.value.failedMobiles.map((mobile) => [mobile]) // A2开始是内容
    ]

    // 创建工作表
    const ws = XLSX.utils.aoa_to_sheet(wsData)

    // 创建工作簿
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '失败手机号')

    // 生成Excel文件并下载
    const fileName = `导入失败手机号_${new Date().toISOString().slice(0, 10)}.xlsx`
    XLSX.writeFile(wb, fileName)

    Message.success('失败列表已下载')
  } catch (error) {
    console.error('下载失败:', error)
    Message.error('下载失败，请重试')
  }
}

defineExpose({ onOpen })
</script>

<style lang="scss" scoped>
.batch-import-content {
  padding: 10px 0;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  transition: border-color 0.3s;

  &:hover {
    border-color: #3370ff;
  }
}

.import-result {
  margin-top: 20px;
}

.failed-mobiles {
  margin-top: 10px;
  max-height: 120px;
  overflow-y: auto;

  .arco-tag {
    margin: 2px 4px 2px 0;
  }
}
</style>
